package com.absorbx.jcr.dao.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.jcr.ImportUUIDBehavior;
import javax.jcr.RepositoryException;
import javax.jcr.Session;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springmodules.jcr.JcrCallback;
import org.springmodules.jcr.JcrTemplate;

import com.absorbx.jcr.dao.JcrTools;

public class JcrToolsImpl implements JcrTools {

    protected final Log log = LogFactory.getLog(JcrToolsImpl.class);
    @Autowired
    @Qualifier("jcrTemplate")
    private JcrTemplate jcrTemplate = null;

    public void setJcrTemplate(JcrTemplate jcrTemplate) {
        this.jcrTemplate = jcrTemplate;
    }

    @Override
    public void exportNode(final String absPath, final String fileName, final boolean skipBinary,
            final boolean noRecurse) {
        jcrTemplate.execute(new JcrCallback() {

            public Object doInJcr(Session session) throws IOException, RepositoryException {
                BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(fileName));
                session.exportDocumentView(absPath, bufferedOutputStream, skipBinary, noRecurse);
                bufferedOutputStream.close();
                return null;
            }

        });

    }

    @Override
    public void importNode(final String absPath, final String fileName, final int importUUIDBehaviour) {
        BufferedInputStream bufferedInputStream;
        try {
            bufferedInputStream = new BufferedInputStream(new FileInputStream(fileName));
            jcrTemplate.importXML(absPath, bufferedInputStream,
                    ImportUUIDBehavior.IMPORT_UUID_COLLISION_REMOVE_EXISTING);
            jcrTemplate.save();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void backupRepository(final String fileName) {
        jcrTemplate.execute(new JcrCallback() {

            public Object doInJcr(Session session) throws IOException, RepositoryException {
                BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(fileName));
                session.exportDocumentView("/", bufferedOutputStream, false, false);
                bufferedOutputStream.close();
                return null;
            }

        });

    }
}
